/**
 * @Author: douxuefeng
 * @Date: 2020/11/19 上午9:24
 * @File: start_app
 * @Desc:
 */
package app

import (
	comm "gitee.com/douxuefeng/go-common"
	"gitee.com/douxuefeng/go-iris/config"
	"gitee.com/douxuefeng/go-iris/route"
	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/core/router"
	"github.com/kataras/iris/v12/middleware/recover"
)

func init()  {
	InitApp()
}
func StartApp()  {
	defer comm.CloseDb()
	app := newApp()
	route.ApiRoute(app)
	addr := config.GetConfig().Addr
	app.Run(iris.Addr(addr), iris.WithConfiguration(iris.Configuration{
		DisableStartupLog:                 false,
		DisableInterruptHandler:           false,
		DisablePathCorrection:             false,
		EnablePathEscape:                  false,
		FireMethodNotAllowed:              true,
		DisableBodyConsumptionOnUnmarshal: false,
		DisableAutoFireStatusCode:         false,
		EnableOptimizations:               true,
		TimeFormat:                        "2006-01-02 15:04:05",
		Charset:                           "UTF-8",
	}))

}
func newApp() *iris.Application {
	app := iris.New()
	app.Use(recover.New())
	cors := cors.New(cors.Options{
		AllowedOrigins:     []string{"*"},
		AllowedMethods:     []string{"PUT", "PATCH", "GET", "POST", "OPTIONS", "DELETE"},
		AllowedHeaders:     []string{"*"},
		ExposedHeaders:     []string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
		MaxAge:             3600,
		AllowCredentials:   true,
	})
	app.UseRouter(cors)
	app.AllowMethods(iris.MethodOptions)
	app.OnAnyErrorCode(func(ctx iris.Context) {
		ctx.StopWithJSON(ctx.GetStatusCode(), map[string]interface{}{
			"code": ctx.GetStatusCode(),
			"msg": "Oups something went wrong, try again!",
			"path": ctx.Path(),
		})
	})
	//注册模板文件路径
	app.RegisterView(iris.HTML("./view",".html").Reload(true))
	// 加载静态文件路径
	app.HandleDir("/", iris.Dir("./statics"), iris.DirOptions{
		Cache:             router.DirCacheOptions{
			Enable:          true,
			CompressMinSize: 5 * iris.MB,
		},		Compress:          true,
	})
	return app
}